


import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;


import org.json.JSONArray;
import org.json.JSONObject;

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

public class DistributeDorPanel extends JPanel {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private JTextField TF_name;
	private JTextField TF_number;
	private final ButtonGroup BG_sex = new ButtonGroup();
	private JTable table;
	private DefaultTableModel model;
	private JTextField TF_note;
	private Vector<Object[]> all_data;
	private JLabel L_name;
	private JLabel L_number;
	private JLabel L_sex;
	private JRadioButton RB_boy;
	private JRadioButton RB_girl;
	private JLabel L_note;
	public JComboBox<String> comboBox;
	private JScrollPane scrollPane;
	private JButton B_enter;
	private JButton B_clear;

	/**
	 * Create the panel.
	 */
	private boolean checkTextLengh(String text,int len,String Name){
		if(text.length()>len)
		{
			JOptionPane.showMessageDialog(null,Name+"不得超过"+len+"个字符",Name+"错误",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	private boolean check_student(String str){
		try{
			JSONObject obj = new JSONObject(new SocketOp().request("{\"method\":\"get_student\",\"student_number\":\""+str+"\"}"));
			if(obj.has("student_number")&&obj.getString("student_number").equals(str)){
				return false;//已存在
			}else{
				return true;//不存在
			}
		}catch(Exception e){
			return true;//不存在
		}

	}
	private boolean check_file_name(String str){
		for(int i=0;i<str.length();i++)
		{
			if(Character.isDigit(str.charAt(i))||Character.isLetter(str.charAt(i))||str.charAt(i)=='-'||str.charAt(i)=='_'){
				continue;
			}else{
				return false;
			}
		}
		return true;

	}

	public boolean updateData(String sendMsg)
	{
		try{
			while(model.getRowCount()>0)
				model.removeRow(model.getRowCount()-1);
			all_data.clear();

			JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
		//	JOptionPane.showMessageDialog(null, obj.toString());

			if(obj.has("result"))
			{

				JSONArray arr = new JSONArray(obj.get("result").toString());
				ArrayList<String> arrStr = new ArrayList<String>();

				for(int i=0;i<arr.length();i++){
					arrStr.add(arr.get(i).toString());
				//	JOptionPane.showMessageDialog(null, arrStr.get(i));
				}
				arrStr.sort(null);
				for(int i=0;i<arrStr.size();i++)
				{

					JSONObject roomObj = new JSONObject(new SocketOp().request(new String("{\"method\":\"get_room\",\"room_name\":\""+arrStr.get(i)+"\"}")));
					//JOptionPane.showMessageDialog(null, roomObj.toString());
					if(comboBox.getSelectedIndex()==1){
						if(roomObj.getInt("room_size")>roomObj.getInt("room_people")){
							all_data.addElement(new Object[]{roomObj.get("room_name").toString(),roomObj.get("room_sex").toString(),roomObj.getInt("room_size"),roomObj.getInt("room_people"),roomObj.get("room_note").toString()});
							model.addRow(new Object[]{roomObj.get("room_name").toString(),roomObj.get("room_sex").toString(),roomObj.getInt("room_size"),roomObj.getInt("room_people"),roomObj.get("room_note").toString()});
						}
					}else{
						all_data.addElement(new Object[]{roomObj.get("room_name").toString(),roomObj.get("room_sex").toString(),roomObj.getInt("room_size"),roomObj.getInt("room_people"),roomObj.get("room_note").toString()});
						model.addRow(new Object[]{roomObj.get("room_name").toString(),roomObj.get("room_sex").toString(),roomObj.getInt("room_size"),roomObj.getInt("room_people"),roomObj.get("room_note").toString()});
					}

				}
			}
		}catch(Exception e1){
			JOptionPane.showMessageDialog(null, e1);
		}
		return true;
	}

	public DistributeDorPanel() {
		setToolTipText("");
		setLayout(null);
		L_name = new JLabel("姓名");
		L_name.setHorizontalAlignment(SwingConstants.RIGHT);
		L_name.setBounds(54, 32, 54, 15);
		setBorder(BorderFactory.createTitledBorder("distribute"));
		add(L_name);

		TF_name = new JTextField();
		TF_name.setBounds(118, 29, 295, 21);
		add(TF_name);
		TF_name.setColumns(10);

		L_number = new JLabel("学号");
		L_number.setHorizontalAlignment(SwingConstants.RIGHT);
		L_number.setBounds(54, 57, 54, 15);
		add(L_number);

		TF_number = new JTextField();
		TF_number.setBounds(118, 54, 295, 21);
		add(TF_number);
		TF_number.setColumns(10);

		L_sex = new JLabel("性别");
		L_sex.setHorizontalAlignment(SwingConstants.RIGHT);
		L_sex.setBounds(54, 82, 54, 15);
		add(L_sex);

		RB_boy = new JRadioButton("男");

		RB_boy.setSelected(true);
		BG_sex.add(RB_boy);
		RB_boy.setBounds(118, 78, 54, 23);
		add(RB_boy);

		RB_girl = new JRadioButton("女");
		BG_sex.add(RB_girl);
		RB_girl.setBounds(174, 78, 54, 23);
		add(RB_girl);

		L_note = new JLabel("备注");
		L_note.setHorizontalAlignment(SwingConstants.RIGHT);
		L_note.setBounds(54, 107, 54, 15);
		add(L_note);

		scrollPane = new JScrollPane();
		scrollPane.setBorder(null);
		scrollPane.setBounds(74, 180, 358, 206);
		add(scrollPane);
		all_data = new Vector<Object[]>();
		table = new JTable();
		table.setFont(new Font("楷体", Font.PLAIN, 15));
		table.setShowGrid(false);
		table.setShowVerticalLines(false);
		scrollPane.setViewportView(table);
		String[] headers = {"寝室号","性别","容量","人数","备注"};
		Object[][] cellData = null;
		model = new DefaultTableModel(cellData, headers) {
			/**
			 *
			 */
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		table.setModel(model);
		table.setRowHeight(30);


		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


		table.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		table.setBorder(null);
		table.setBackground(getBackground());
		B_enter = new JButton("确认");

		B_enter.setBounds(135, 396, 93, 23);
		add(B_enter);

		B_clear = new JButton("清空");
		B_clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				table.clearSelection();
				TF_name.setText("");
				TF_number.setText("");
				TF_note.setText("");
				RB_boy.setSelected(true);

			}
		});
		B_clear.setBounds(274, 396, 93, 23);
		add(B_clear);

		comboBox = new JComboBox<String>();
		comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"显示全部", "显示可选"}));

		comboBox.setSelectedIndex(1);
		comboBox.setBounds(74, 151, 359, 21);
		add(comboBox);

		TF_note = new JTextField();
		TF_note.setBounds(118, 104, 295, 21);
		add(TF_note);
		TF_note.setColumns(10);

		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				String sendMsg = "{\"method\":\"show_room\",\"room_sex\":\""+(RB_boy.isSelected()?"boy":"girl")+"\",\"room_status\":\""+(comboBox.getSelectedIndex()==0?"all":"avilable")+"\"}";
				updateData(sendMsg);
				//JOptionPane.showMessageDialog(null, comboBox.getSelectedItem());
				//JOptionPane.showMessageDialog(null, comboBox.getSelectedIndex());
			}
		});

		RB_boy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String sendMsg = "{\"method\":\"show_room\",\"room_sex\":\"boy\",\"room_status\":\""+(comboBox.getSelectedIndex()==0?"all":"avilable")+"\"}";
				updateData(sendMsg);
			}
		});
		RB_girl.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String sendMsg = "{\"method\":\"show_room\",\"room_sex\":\"girl\",\"room_status\":\""+(comboBox.getSelectedIndex()==0?"all":"avilable")+"\"}";
				updateData(sendMsg);
			}
		});
		B_enter.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				if(TF_name.getText().equals("")){
					JOptionPane.showMessageDialog(null, "姓名不得为空", "姓名错误", JOptionPane.ERROR_MESSAGE);
					return;
				}
				if(!checkTextLengh(TF_name.getText(),20,"姓名")){
					return;
				}else if(!check_file_name(TF_number.getText())){
					JOptionPane.showMessageDialog(null, "学号需为不已0开头的12位数字","导入失败",JOptionPane.ERROR_MESSAGE);
					return;
				}else if(!check_student(TF_number.getText())){
					JOptionPane.showMessageDialog(null, "当前学生的学号已经被占用，请核对学号姓名是否有误","导入失败",JOptionPane.ERROR_MESSAGE);
					return;
				}else if(!checkTextLengh(TF_note.getText(),200,"备注")){
					return;
				}else if(table.getSelectedRow()<0){
					JOptionPane.showMessageDialog(null, "未选择寝室", "导入失败", JOptionPane.WARNING_MESSAGE);
					return;
				}else if(Integer.parseInt(all_data.get(table.getSelectedRow())[2].toString())<=Integer.parseInt(all_data.get(table.getSelectedRow())[3].toString())){
					JOptionPane.showMessageDialog(null, "当前寝室已满", "导入失败", JOptionPane.WARNING_MESSAGE);
					return;
				}
				try{
					String sendMsg1 ="{\"method\":\"import_student\",\"student_name\":\""+TF_name.getText()+"\",\"student_number\":\""+TF_number.getText()+"\",\"student_sex\":\""+(RB_boy.isSelected()?"boy":"girl")+"\",\"student_room\":\""+all_data.get(table.getSelectedRow())[0].toString()+"\",\"student_note\":\""+TF_note.getText()+"\"}";
					JSONObject obj = new JSONObject(new SocketOp().request(sendMsg1));
					if(obj.has("result")&&obj.getString("result").equals("success")){
						JOptionPane.showMessageDialog(null, "成功导入一个数据", "导入成功", JOptionPane.INFORMATION_MESSAGE);
					}else{
						JOptionPane.showMessageDialog(null, "导入失败", "导入失败", JOptionPane.ERROR_MESSAGE);
					}
					table.clearSelection();
					TF_name.setText("");
					TF_number.setText("");
					TF_note.setText("");
					String sendMsg = "{\"method\":\"show_room\",\"room_sex\":\""+(RB_boy.isSelected()?"boy":"girl")+"\",\"room_status\":\""+(comboBox.getSelectedIndex()==0?"all":"avilable")+"\"}";
					updateData(sendMsg);

				}catch(Exception e){
					JOptionPane.showMessageDialog(null, "导入失败", "导入失败", JOptionPane.ERROR_MESSAGE);
				}

			}
		});

	}
}
